const path = require("path");
const { ipcRenderer } = require("electron");
const Types = require(path.join(__dirname, "../src/const/eventName"));

function $(selector) {
  return window.document.querySelector(selector);
}

document.addEventListener("DOMContentLoaded", function () {
  // 获取之前存储的位置
  ipcRenderer.send(Types.GETSETTINGDOCPATH);
  ipcRenderer.send(Types.GETOSSCONFIG);

  ipcRenderer.on(Types.GETSETTINGDOCPATHREPLY, function (_, path) {
    $("#location").value = path;
  });
  ipcRenderer.on(Types.GETOSSCONFIGREPLY, function (_, config) {
    $("#accessKeyId").value = config.accessKeyId || "";
    $("#accessKeySecret").value = config.accessKeySecret || "";
    $("#bucket").value = config.bucket || "";
    $("#folder").value = config.folder || "";
    $("#region").value = config.region || "";
  });

  ipcRenderer.on(Types.OPENSETTINGDIAREPLY, function (_, { filePaths }) {
    $("#location").value = filePaths[0];
  });

  // tab切换
  $("#saveTab").addEventListener("click", function (e) {
    if (!$("#saveTab").classList.contains("active")) {
      $("#saveTab").classList.add("active");
      $("#ossTab").classList.remove("active");
      $("#ossWrap").classList.add("hide");
      $("#saveWrap").classList.remove("hide");
    }
  });
  $("#ossTab").addEventListener("click", function (e) {
    if (!$("#ossTab").classList.contains("active")) {
      $("#ossTab").classList.add("active");
      $("#saveTab").classList.remove("active");
      $("#saveWrap").classList.add("hide");
      $("#ossWrap").classList.remove("hide");
    }
  });

  $("#select").addEventListener("click", function () {
    ipcRenderer.send(Types.OPENSETTINGDIA);
  });

  $("#save").addEventListener("click", function () {
    ipcRenderer.send(Types.SAVESETTINGPATH, $("#location").value);
  });

  // oss
  $("#ossSave").addEventListener("click", () => {
    const fVal = $("#folder").value || "";
    const folder = !fVal || fVal.endsWith("/") ? fVal : `${fVal}/`;
    const config = {
      region: $("#region").value || "",
      accessKeyId: $("#accessKeyId").value || "",
      accessKeySecret: $("#accessKeySecret").value || "",
      bucket: $("#bucket").value || "",
      folder,
    };
    ipcRenderer.send(Types.SETOSSCONFIG, config);
  });

  //关闭设置
  $("#close").addEventListener("click", () => {
    ipcRenderer.send(Types.CLOSESETTINGWINDOW);
  });
});
